define(function (require, exports, module) {
    var angular = require('angular');
    require("@yunke/jquery_pagination");
    require('angular-ui');
    require("../../../plugins/select2/select2");
    require('../contract-common');
    require('../contract-attribute');
    var dialog = require('@yunke/art-dialog').default;
    var myMath = require('../../common/my-math');
    var authorize = require('../../authorize');
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    angular.module('ContractPerformance', ['ContractAttribute'])
        .filter('percent', function () {
            return function (num) {
                return num * 100;
            }
        })
        .filter('sumBackAmountP', function () {
            /**
             * 应收信息下回款信息总额
             */
            return function(items){
                if(items){
                    var amount = 0;
                    $.each(items, function (i, d) {
                        amount = myMath.add(amount, parseFloat(d.payment_amount));
                    })
                    return amount;
                }
            }
        })
        .filter('sumPaymentAmountP', function () {
            /**
             * 已录入回款业绩信息
             */
            return function (items) {
                var amount = 0;
                $.each(items, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.achievement_amount));
                })
                return amount;
            }
        })
        .filter('remainPaymentAmountP', function () {
            /**
             * 剩余可录入回款业绩信息
             */
            return function (paymentAmountP, backAmountP) {
                var pAmount = 0,
                    bAmount = 0;

                if(backAmountP){
                    $.each(paymentAmountP, function (i, d) {
                        if (d['__type'] == 'delete') {
                            return;
                        }
                        pAmount = myMath.add(pAmount, parseFloat(d.achievement_amount));
                    });
                    $.each(backAmountP, function (i, d) {
                        if (d['__type'] == 'delete') {
                            return;
                        }
                        bAmount = myMath.add(bAmount, parseFloat(d.payment_amount));
                    });
                }


                return bAmount - pAmount;
            }
        })
        .filter('sumSignAmount', function () {
            return function (incomes) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.achievement_amount));
                });
                return amount;
            }
        })
        .filter('remainSignAmount', function () {
            return function (incomes, contract) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.achievement_amount));
                });
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '39e61716-1240-85fa-d5bb-15a7f3d1d837') {
                        //云客签约-直属区域/云客签约-联营区域/云客直销
                        //收入金额汇总 = 签约金额
                        return myMath.sub(contract.sign_amount, amount);
                    } else {
                        //其他：收入金额汇总=结算金额
                        return myMath.sub(contract.balance_amount, amount);
                    }
                }

                return 0;
            }
        })
        .filter('signOrBalanceAmount', function () {
            return function (contract) {
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '39e61716-1240-85fa-d5bb-15a7f3d1d837') {
                        //云客签约-直属区域/云客签约-联营区域/云客直销
                        //收入金额汇总 = 签约金额
                        return contract.sign_amount;
                    } else {
                        //其他：收入金额汇总=结算金额
                        return contract.balance_amount;
                    }
                }
                return 0;
            }
        })
        .filter('signOrBalanceLabel', function () {
            return function (contract) {
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '39e61716-1240-85fa-d5bb-15a7f3d1d837') {
                        //云客签约-直属区域/云客签约-联营区域/云客直销
                        //收入金额汇总 = 签约金额
                        return '签约金额';
                    } else {
                        //其他：收入金额汇总=结算金额
                        return '结算金额';
                    }
                }
                return 0;
            }
        })
        .filter('setAttributeName',function (){
            return 0;
        })
        .controller('contractPerformanceCtrl', ['$scope', '$filter', '$routeParams','contractAttributeService', 'contractCommonService', function ($scope,$filter, $routeParams,contractAttributeService, contractCommonService) {
            //合同业绩信息
            $scope.contractBaseInfo = {customer_property: 0, contract_status: 0};
            //是否区域角色
            authorize.getUserInfoPromise().then((userinfo) => {
                $scope.areaRole = userinfo.areaRole;
            });
            $scope.contractPfmInfo = {
                signAchievements: [],
                paymentAchievement: []
            };

            //产品列表
            var contractId = $routeParams.id;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
            }

            $scope.attribute_name_text = ['新增','增购','续签'];

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    //合同基本信息
                    contractCommonService.getContract(contractId, function (data) {
                        $scope.contractBaseInfo = data.contract;
                        $scope.pfmAttributeNameArr = [];
                        $scope.paymentAttributeNameArr = [];
                        $scope.$applyAsync();
                    });

                    //获取已回款金额
                    contractCommonService.getContractUnifiedInfo(contractId, function (data) {
                        $scope.receivableInfo = data;
                        $scope.$applyAsync();
                    });


                    //合同业绩信息
                    var url = api_prefix + 'contract/get-sign-achievement';
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: {contractId: contractId},
                        success: function (res) {
                            if (res.retCode === "0") {

                                var data = res.data;
                                // console.log(data);
                                $scope.contractPfmInfo = data;

                                if (!$scope.contractPfmInfo.signAchievements[0].manager_name) {
                                    $scope.contractPfmInfo.signAchievements[0].manager_name = '';
                                }


                                //签约业绩  false,false,false => ['false','false','false']
                                $.map($scope.contractPfmInfo.signAchievements,function(n,i){
                                    if(n.attribute_name != null){
                                        n.attribute_name = n.attribute_name.split(',');
                                    }else{
                                        //不存在 ,默认获取合同属性
                                        if($scope.contractBaseInfo.attribute_name != null){
                                            n.attribute_name = $scope.contractBaseInfo.attribute_name.split(",");
                                        } else {
                                            n.attribute_name = ['false','false','false']
                                        }
                                    }
                                });

                                //回款业绩 false,false,false => ['false','false','false']
                                $.map($scope.contractPfmInfo.paymentAchievement,function(n,i){
                                    if(n.attribute_name != null){
                                        n.attribute_name = n.attribute_name.split(',');
                                    }else{ //不存在 ,默认获取合同属性
                                        if($scope.contractBaseInfo.attribute_name != null){
                                            n.attribute_name = $scope.contractBaseInfo.attribute_name.split(",");
                                        } else {
                                            n.attribute_name = ['false','false','false']
                                        }
                                    }
                                });

                                $scope.$applyAsync();
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                }
            };


            //下拉框设置
            //业绩归属人
            $scope.ddlConfigBelongBy = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.belong_name = newVal.text;
                        scope.area_by = newVal.BUGUID;
                        scope.abu_by = newVal.AubGUID;
                        scope.department_by = newVal.DepartmentId
                        scope.department_name = newVal.DepartmentName;
                        scope.area_name = newVal.BUName;
                    }
                },
                formatResult: formatProposer,
                formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
            };

            //ERP业绩归属人
            $scope.ddlConfigErpBelongBy = {
                allowClear: true,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        newVal || (newVal = {});
                        scope.erp_achievement_belong_name = newVal.text || '';
                        scope.erp_achievement_belong_abu = newVal.AubGUID || '';
                        scope.erp_achievement_belong_abu_owner = newVal.AbuOwnerGUID || '';
                        scope.erp_achievement_belong_bu_manager = newVal.BuManagerGUID || '';

                        scope.erp_achievement_belong_abu_name = newVal.AubName || '';
                        scope.erp_achievement_belong_abu_owner_name = newVal.AbuOwnerName || '';
                        scope.erp_achievement_belong_bu_manager_name = newVal.BuManagerName || '';
                    }
                }
            };

            //EPR客户经理
            $scope.ddlConfigManagerBy = {
                allowClear: true,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.manager_name = newVal ? newVal.text : '';
                        scope.erp_achievement_belong_bu = newVal ? newVal.DepartmentId : ''
                        scope.erp_achievement_belong_bu_name = newVal ? newVal.DepartmentName : '';
                    }
                },
                formatResult: formatProposer,
                formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
            };
            function formatProposer(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProposerSelection(repo) {
                return repo.text;
            }

            /**
             * 拆分业绩
             * @param items
             */
            $scope.addSignAchievement = function (items, record) {
                var item;

                if (items == $scope.contractPfmInfo.paymentAchievement) {
                    item = {
                        receivable_item_id: record.receivable_item_id,
                        receivable_item_name: record.receivable_item_name,
                        money_category_item_id: record.money_category_item_id,
                        money_category_item_name: record.money_category_item_name,
                        editMode: 1,
                        received_time: record.received_time,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                } else {
                    item = {
                        editMode: 1,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                }

                items.push(item);
            };

            /**
             * 修改业绩
             * @type {number}
             */
            $scope.editSignAchievement = function (item, idx, items) {
                //先保存原始数据
                item.orginalData = angular.copy(item);
                item.editMode = 2;

                //获取当前修改的人物下拉框
                var n = -2;
                var it;
                for (var i = idx; it = items[i]; i--) {
                    if (it.editMode == 1 || it.editMode == 2) {
                        //每点开一个，会生成2个相同class的元素
                        n += 2;
                    }
                }

                setTimeout(function () {
                    $(".idBelongBy1").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.belong_name
                    });
                    $(".idManagerBy1").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.manager_name
                    });
                    $(".idBelongBy2").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.belong_name
                    });
                    $(".idManagerBy2").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.manager_name
                    });
                    $(".idErpBelongBy").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.erp_achievement_belong_name
                    });
                    $scope.$applyAsync();
                }, 0)

            };

            /**
             * 删除收入
             * @type {number}
             */
            $scope.delSignAchievement = function (item, idx, items) {
                var it;
                var sum = 0;
                for (var i = 0; it = items[i]; i++) {
                    if (!it.editMode || it.editMode == 0) {
                        sum++;
                    }
                }
                if (sum <= 1) {
                    util.alert('不可删除唯一确定的业绩！');
                    return
                }
                util.confirm('确定要删除此业绩吗？', {
                    ok: function () {
                        if (item.__type == 'add') {
                            items.splice(idx, 1);
                        } else {
                            angular.extend(item, {__type: 'delete', editMode: 3});
                        }
                        $scope.$applyAsync();
                    }
                });
            };

            /**
             * 保存收入信息
             * @type {number}
             */
            $scope.saveSignAchievement = function (item) {
                if (!item.achievement_amount) {
                    util.alert('业绩金额不能为空');
                    return;
                } else if (!(parseFloat(item.achievement_amount) > 0)) {
                    util.alert('业绩金额必须为数值且大于0');
                    return;
                } else {
                    var arr = item.achievement_amount.split(".");
                    if (arr.length > 2) {
                        util.alert('业绩金额只能输入1位小数点');
                        return
                    } else if (arr[1] && arr[1].length > 2) {
                        util.alert('业绩金额请保留2位小数');
                        return
                    }
                }


                if (!item.belong_by) {
                    util.alert('业绩归属人不能为空');
                    return;
                }

                // 当合同类型为非直属区域时：ERP相关业绩归属不是必填项
                // 云客签约-直属区域 : 7f83719a-fce8-11e4-bed8-00155d02c832
                // 明源签约-直属区域 : 54f8a2b7-fce7-11e4-bed8-00155d02c832
                //10月1日业绩规则变了，这个字段不用强控
                //if($scope.contractBaseInfo.contract_property_id === '7f83719a-fce8-11e4-bed8-00155d02c832' || $scope.contractBaseInfo.contract_property_id === '54f8a2b7-fce7-11e4-bed8-00155d02c832'){
                //    if (!item.manager_by) {
                //        util.alert('ERP客户经理不能为空');
                //        return;
                //    }
                //}


                item.editMode = 0;
                $scope.$applyAsync();
            };

            /**
             * 取消保存
             * @type {number}
             */
            $scope.cancelSignAchievement = function (item, idx, items) {
                if (item.editMode == 1) {
                    items.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }

            };




            //能否保存判断
            $scope.saveEnabled = function () {
                var sign = $scope.contractPfmInfo.signAchievements;
                var payment = $scope.contractPfmInfo.paymentAchievement;
                var n = 0;
                $.grep(sign, function (d, i) {
                    if (d.editMode == 1 || d.editMode == 2) {
                        n++;
                    }
                });
                $.grep(payment, function (d, i) {
                    if (d.editMode == 1 || d.editMode == 2) {
                        n++;
                    }
                });
                return n;
            };



            /**
             * 保存信息
             */
            $scope.save = function () {


                var remainAchievement = $filter('remainPaymentAmountP')($scope.contractPfmInfo.paymentAchievement,$scope.receivableInfo.payments);

                if(remainAchievement != 0){
                    util.alert('回款业绩金额总额不等于回款金额 !');
                    return false;
                }


                var url = api_prefix + 'contract/save-sign-achievement';

                //计算
                var restSignAmount = $filter('remainSignAmount')($scope.contractPfmInfo.signAchievements,$scope.contractBaseInfo),
                    signOrBalanceName= $filter('signOrBalanceLabel')($scope.contractBaseInfo);


                if(restSignAmount != 0){
                    util.alert('签约业绩金额总和不等于' + signOrBalanceName);
                    return false;
                }

                if ($scope.contractBaseInfo.is_cancelled == 0) {

                    $.map($scope.contractPfmInfo.signAchievements,function(n,i){
                        n.attribute_name = n.attribute_name.toString();
                    });

                    $.map($scope.contractPfmInfo.paymentAchievement,function(n,i){
                        n.attribute_name = n.attribute_name.toString();
                    });


                    var data = {
                        contractId: contractId,
                        drawProjectNumeric: $scope.contractPfmInfo.draw_project_numeric,
                        projectNumeric: $scope.contractPfmInfo.project_numeric,
                        achievementRemark: $scope.contractBaseInfo.achievement_remark,
                        signAchievements: $scope.contractPfmInfo.signAchievements,
                        paymentAchievements: $scope.contractPfmInfo.paymentAchievement
                    };
                }



                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (res) {
                        if (res.retCode === "0") {
                            util.alert('保存成功');
                            $scope.loadContract(contractId);
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error: function () {
                        util.alert('系统维护，请稍候重试！');
                    }
                });

            };

            //页面初始化
            $scope.init = function () {
                $scope.loadContract(contractId);
            };
            $scope.init();
        }]);
});
